//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.Caching;
using CommunityServer.Components;

namespace CommunityServer.Blogs.Components
{
    /// <summary>
    /// Summary description for WeblogRssHandler.
    /// </summary>
    public class WeblogRssHandler : BaseWeblogSyndicationHandler
    {
        public WeblogRssHandler()
        {
        }

        protected int CategoryID = 0;
		protected int PostID = 0;
		protected string[] Tags = null;
		protected bool AndTags = false;

        protected override string CacheKey
        {
            get
            {
				if(CategoryID > 0)
					return string.Format("Weblog:{0}:CategoryRss:{1}",CurrentSection.SectionID,CategoryID);
				else if(this.Tags != null)
					return string.Format("Weblog:{0}:TagsRss:{1}:AndTags:{2}", CurrentSection.SectionID,String.Join(",", Tags), AndTags);
				else if(PostID > 0)
					return string.Format("Weblog:{0}:PostRss:{1}",CurrentSection.SectionID,PostID);
				else
                    return string.Format("Weblog:{0}:IndividualRss",CurrentSection.SectionID);
            }
        }

        protected override int CacheTime
        {
            get
            {
                if(this.CategoryID > 0)
                    return 10;
				else if(this.Tags != null)
					return 10;
				else if(this.PostID > 0)
                    return 5;
                else
                    return base.CacheTime;
            }
        }

        protected override CacheItemPriority Priority
        {
            get
            {
                if(this.CategoryID > 0)
                    return CacheItemPriority.BelowNormal;
				else if(this.Tags != null)
					return CacheItemPriority.BelowNormal;
				else if(this.PostID > 0)
                    return CacheItemPriority.Low;
                else
                    return CacheItemPriority.Normal;
            }
        }
        

	
        /// <summary>
        /// Process the Weblog RSS feed, checking for external a feed redirect and any specified tags or categories.
        /// </summary>
        protected override void ProcessFeed()
        {

            if(Context.Request.QueryString["CategoryID"] != null)
            {
                double cid = 0;
                if(Double.TryParse( Context.Request.QueryString["CategoryID"], System.Globalization.NumberStyles.Integer, null, out cid ))
                    this.CategoryID = (int)cid;
            }
			else if(CSContext.Current.Tags != null)
			{
				this.Tags = CSContext.Current.Tags;
				if (Context.Request.QueryString["andTags"] != null)
				{
					double andTags = 0;
					if(Double.TryParse( Context.Request.QueryString["andTags"], System.Globalization.NumberStyles.Integer, null, out andTags ))
						this.AndTags = Convert.ToBoolean((int)andTags);
				}
			}
			else if(Context.Request.QueryString["PostID"] != null)
			{
				double pid = 0;
				if(Double.TryParse( Context.Request.QueryString["PostID"], System.Globalization.NumberStyles.Integer, null, out pid ))
					this.PostID = (int)pid;
			}


            // Check if an external feed url exists for this blog
            if (!Globals.IsNullorEmpty(((Weblog)CurrentSection).ExternalFeedUrl))
            {
                // Redirect to external url unless this is being accessed via private url, or a specific tag/category/post was requested
                if (Globals.IsNullorEmpty(Context.Request.QueryString["private"]) && this.Tags == null && this.CategoryID == 0 && this.PostID == 0)
                {
                    Context.Response.RedirectLocation = ((Weblog)CurrentSection).ExternalFeedUrl;
                    Context.Response.StatusCode = 301;
                    Context.Response.End();
                }
            }
            
            base.ProcessFeed();
        }


        protected override CachedFeed BuildFeed()
        {
            BaseRssWriter writer = null;
			BlogThreadQuery query = CreateQuery();
			ThreadSet threads = WeblogPosts.GetBlogThreads(query, true);

			if(CategoryID > 0)
			{
				PostCategory cat = PostCategories.GetCategory(CategoryID, CurrentSection.SectionID);
				writer = new WeblogCategoryRssWriter(threads.Threads, CurrentWeblog, this.BaseUrl, cat);

			}
			else if(Tags != null)
			{
				writer = new WeblogTagsRssWriter(threads.Threads, CurrentWeblog, this.BaseUrl, Tags);
			}
			else
			{
				writer = new WeblogRssWriter(threads.Threads, CurrentWeblog, this.BaseUrl);
			}
            
			DateTime dt =  threads.Threads.Count > 0 ? ((WeblogPost)threads.Threads[0]).PostDate : DateTime.Now;
			
			return new CachedFeed(dt, null, writer.GetXml());

        }

    	protected virtual BlogThreadQuery CreateQuery()
    	{
    		BlogThreadQuery query = BlogThreadQuery.CreateNewSingleBlogQuery(CurrentSection.SectionID);
			query.BlogPostType = BlogPostType.Post;
    		query.PageIndex = 0;
    		query.PageSize = BlogConfig.IndividualPostCount;
    		query.FirstPageOnly = false;

			if (CategoryID > 0)
				query.CategoryID = this.CategoryID;
			else if (Tags != null && Tags.Length > 0)
			{
				query.Tags = Tags;
				query.LogicallyOrTags = !AndTags;
			}
			else if (this.PostID > 0)
				query.PostID = this.PostID;
			else
				query.PostConfig = BlogPostConfig.IsAggregated;

			return query;
    	}


    }
}
